<template>
	<!-- <page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta> -->
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>
			
			<uni-forms ref="baseForm" :modelValue="chuchaiApplyForm" :border="true" labelWidth="100px"
				label-position="left">
				<view class="tips">
					填写说明：<br>
					1、职工出差2天及以下，需部门领导、分管领导审批；3天及以上需要主要领导审批。<br>
					2、部门负责人出差1天及以上，需分管领导、主要领导审批。<br>
					3、乘坐飞机或出差目的地为市域范围之外的，需要单位主要领导审批。<br>
					4、出差目的地为市域范围以内的，出差天数原则不超过1天，出差目的地需填写具体的出差单位或地址。<br>
					5、出差交通工具为单位公务车的，需另行履行用车手续。<br>
				</view>
				<uni-forms-item label="出差人">
					<view class="text-bg">{{userName}}</view>
				</uni-forms-item>
				<uni-forms-item label="开始时间" required>
					<uni-datetime-picker @click="chuanci()" @change="dateChangeStart" @maskClick="chuanci2()"  type="date" return-type="string" v-model="chuchaiApplyForm.startDate"/>
				</uni-forms-item>
				<uni-forms-item label="结束时间" required>
					<uni-datetime-picker @click="chuanci()" @change="dateChangeEnd" @maskClick="chuanci2()"  type="date" return-type="string" v-model="chuchaiApplyForm.endDate"/>
				</uni-forms-item>
				<uni-forms-item label="出差天数">
					<uni-easyinput :inputBorder="false" :placeholder="chuchaiDaysStr()" disabled ></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="部门" required>
					<view class="text-bg">{{ userInfo.departmentName }}</view>
				</uni-forms-item>
				
				<uni-forms-item label="出差事由" required>
					<uni-easyinput type="textarea"  @change="chuanci2" @input="chuanci2"  autoHeight v-model="chuchaiApplyForm.reason" />
				</uni-forms-item>
				
				<uni-forms-item label="出发地" required>
					<uni-easyinput type="text" autoHeight v-model="chuchaiApplyForm.chufa" />
				</uni-forms-item>
				<uni-forms-item label="目的地" required>
					<uni-easyinput type="text" autoHeight v-model="chuchaiApplyForm.destination" @change="isyancheng"/>
				</uni-forms-item>

				<uni-forms-item label="举办方是否" required  label-position="top">
					<checkbox-group  @change="baoChange">
						<uni-row>
						<view v-for="(yz,idx) in baoList" :key="idx">
							<uni-col :span="8">
								<view class="check-css"  >
									<checkbox :value="yz">{{yz}}</checkbox>
								</view>
							</uni-col>
						</view>
						</uni-row>
					</checkbox-group>
				</uni-forms-item>

				<uni-forms-item label="交通工具" required>
					<uni-data-checkbox v-model="chuchaiApplyForm.jiaotong" :localdata="jiaotongTypeStr" @change="yanchengChange" />
				</uni-forms-item>

				<!-- 附件模块 -->
				<uni-forms-item label="附件"></uni-forms-item>
				<view v-for="(item,index) in files.values()" :key="index">
					<view v-if="item.type=='success' && item.size <=1048576">[{{(item.size/1024).toFixed(2)}}KB] {{item.name.substring(0,30)}}
					
					</view>
					<view v-if="item.type=='success' && item.size >1048576">[{{(item.size/1048576).toFixed(2)}}MB] {{item.name.substring(0,30)}}
						
					</view>
					<view v-if="item.type!='success'"><i style="color: royalblue;">上传{{item.progress}}%</i> {{item.name.substring(0,30)}}</view>
				</view>
				<lsj-upload ref="lsjUpload" childId="upload1" height="40px" :size="uploadconfig.size"
					:instantly="uploadconfig.instantly" :formats='uploadconfig.formats' :option="option"
					@change="onChange" @progress="onprogress" @uploadEnd="onuploadEnd">
					<button class="btn-fujian" @click="fuckyou">添加附件</button>
					
				</lsj-upload>
				<view class="tips">说明：从此上传图片将无法预览，单个文件请控制在100MB以内</view>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in chuchaiApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.chufa}}-{{item.destination}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>开始时间：{{item.startDate}}</view>
						<view>结束时间：{{item.endDate}}</view>
						<view>天数：{{item.days}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>

	</view>
</template>

<script>
	import store from '../../store'
	import moment from 'moment'
	import {websock} from '../../net/websock'
	import {uploadconfig} from '../../const'
	
	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url:uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats:uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动

				show:false,
				store,
				currentIndex: 0,
				items: ['申请出差', '出差历史'],
				baoList: ['无', '包餐饮', '包交通', '包住宿'],
				jiaotongTypeStr: [{text:"铁路",value: "铁路"},{text:"汽车",value: 1},{text:"飞机",value: "飞机"},{text:"公务车",value: "公务车"},{text:"轮船",value: "轮船"},{text:"包干",value: "包干"},{text:"其他",value: "其他"}],
				userInfo: {},
				userName: '',
				applyRecord: [],
				moreStatus: 'more',
				departNames: [],
				departIds: [],
				departIndex: 0,
				auditors: [], // 审核人
				lingdao: {}, // 领导
				bao: [],
				chuchaiApplyForm: {
					startDate: '',
					endDate: '',
					chufa: '',
					destination: '',
					jiaotong: "",
					reason: '',
					attaches: [],
					auditors: [],
					bao: []
				}
			}
		},
		async onReady() {
			try{
				this.userInfo = await websock.getUserInfo()
				console.log('gongwu chuchai user info', this.userInfo)
				this.userName = this.userInfo.name

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					this.departNames.push(departList[i].name)
					this.departIds.push(departList[i].id)
				}
				console.log('depart list', departList)

				this.auditors = await websock.getAuditors({typ: 1})
				console.log('auditors', this.auditors)
				
				this.lingdao = await websock.getLingdao()
				console.log('my lingdao info', this.lingdao)

				this.checkAuditors()

				this.getNewestRecord()
			}catch(e){
				uni.showToast({title: e.message})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			change(e) {
				this.show = e.show
			},
			// 获取最新的通知
			async getNewestRecord() {
				try{
					if (this.applyRecord.length == 0) {
						let res = await websock.chuchaiApplyRecord({pageCount: 10})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.chuchaiApplyRecord({greaterThan: this.applyRecord[0].id,pageCount: 10})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try{
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.chuchaiApplyRecord({pageCount: 10})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.chuchaiApplyRecord({lessThan: this.applyRecord[this.applyRecord.length - 1].id,pageCount: 10})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			// 附件上传恶心的代码块
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				console.log('fuck you',3)
				if (item.type == 'fail') {
					return uni.showToast({title: '上传失败'})}
				try {
					let res = JSON.parse(item.responseText)
					if (res.code !== 0) {
						return uni.showToast({title: res.message || 'error'})}
					this.chuchaiApplyForm.attaches.push({name: item.name, path: res.data})
				} catch (err) {
					uni.showToast({title: err.message})}
				this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				this.files.set(item.name,item);// 更新当前状态变化的文件
				this.$forceUpdate();// 强制更新视图
			},
			// 文件选择回调
			onChange(files) {
				this.files = files;// 更新选择的文件 
				this.$forceUpdate();// 强制更新视图
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci2(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.show();
				this.$forceUpdate()
			},
			// 强制重置附件按钮,万一出意外点2次按钮至少可以进去
			fuckyou(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide()
				this.$refs.lsjUpload && this.$refs.lsjUpload.show()
				this.$forceUpdate()
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			chuchaiDaysStr() {
				if (this.chuchaiApplyForm.startDate == '' || this.chuchaiApplyForm.endDate == '') return ''
				let diffDays = moment(this.chuchaiApplyForm.endDate).diff(moment(this.chuchaiApplyForm.startDate), 'day')
				if (diffDays < 0) return ''
				return (diffDays + 1) + ' 天'
			},
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.chuchaiApplyForm.auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.chuchaiApplyForm.auditors = data.contactList
						}
					}
				})
			},
			dateChangeStart(e) {
				this.chuchaiApplyForm.startDate = e
				this.dateChange()
			},
			dateChangeEnd(e) {
				this.chuchaiApplyForm.endDate = e
				this.dateChange()
			},
			yanchengChange() {
				this.checkAuditors()
			},
			isyancheng(){
				this.checkAuditors()
			},
			async dateChange() {
				this.chuanci2()

				this.checkAuditors()
			},
			baoChange(e) {
				console.log('bao change', e)
				this.bao = e.detail.value
			},
			addAuditor(info) {
				if (!info.uid) return
				for (let i = 0; i != this.chuchaiApplyForm.auditors.length; i++) {
					if (this.chuchaiApplyForm.auditors[i].uid == info.uid) return
				}

				this.chuchaiApplyForm.auditors.push(info)
			},
			checkAuditors() {

				this.chuchaiApplyForm.auditors = []
				let defaultAuditors = this.auditors.slice()
				console.log('default auditors', defaultAuditors)
				for (let i = 0; i != defaultAuditors.length; i++) {
					if (defaultAuditors[i].sta == '0') {
						this.chuchaiApplyForm.auditors.push(defaultAuditors[i])
					}
				}

				// 请假天数
				let diffDays = moment(this.chuchaiApplyForm.endDate).diff(moment(this.chuchaiApplyForm.startDate), 'day') + 1
				// 是否为科长
				let isKezhang = this.userInfo.uid == this.lingdao.zhijie_lingdao
				// 是否是飞机
				let isFeiji = this.chuchaiApplyForm.jiaotong == '飞机'
				// 目的地是否是盐城
				let isYancheng = this.chuchaiApplyForm.destination != '盐城'
				
				if(diffDays>2 ||(isKezhang && diffDays>0)){
					this.addAuditor({uid: this.lingdao.fenguan_lingdao, name: this.lingdao.fenguan_lingdao_name, positionName: this.lingdao.fenguan_lingdao_position_name})
				}
				if(diffDays>3 ||(isKezhang && diffDays>0)|| isFeiji || isYancheng){
					this.addAuditor({uid: this.lingdao.zhuyao_lingdao, name: this.lingdao.zhuyao_lingdao_name, positionName: this.lingdao.zhuyao_lingdao_position_name})
				}
			},
			async clickApply() {
				console.log('click apply', this.chuchaiApplyForm)

				if (this.chuchaiApplyForm.startDate == '') {
					return uni.showToast({title: '请选择开始时间'})
				}

				if (this.chuchaiApplyForm.endDate == '') {
					return uni.showToast({title: '请选择结束时间'})
				}

				let diffDays = moment(this.chuchaiApplyForm.endDate).diff(moment(this.chuchaiApplyForm.startDate), 'day')
				if (diffDays < 0) return uni.showToast({title: '结束时间应该大于开始时间'})

				if (this.chuchaiApplyForm.reason == '') {
					return uni.showToast({title: '请输入出差事由'})
				}

				if (this.chuchaiApplyForm.chufa == '') {
					return uni.showToast({title: '请输入出发地'})
				}

				if (this.chuchaiApplyForm.destination == '') {
					return uni.showToast({title: '请输入出差目的地'})
				}

				if (this.bao.length == 0) {
					return uni.showToast({title: '请选择包项'})
				}

				if (this.chuchaiApplyForm.auditors.length == 0) {
					return uni.showToast({title: '请选择审核人'})
				}

				let auditors = []
				for (let i = 0; i != this.chuchaiApplyForm.auditors.length; i++) {
					auditors.push({uid: this.chuchaiApplyForm.auditors[i].uid, stepName: this.chuchaiApplyForm.auditors[i].stepName || this.chuchaiApplyForm.auditors[i].positionName})
				}

				try {
					await websock.chuchaiApply({
						department: this.userInfo.departmentName,
						startDate: this.chuchaiApplyForm.startDate,
						endDate: this.chuchaiApplyForm.endDate,
						reason: this.chuchaiApplyForm.reason,
						days: diffDays + 1,
						chufa: this.chuchaiApplyForm.chufa,
						destination: this.chuchaiApplyForm.destination,
						bao: this.bao,
						jiaotong: this.chuchaiApplyForm.jiaotong,
						attaches: this.chuchaiApplyForm.attaches,
						auditors
					})
					uni.showToast({title: '提交成功'})
					this.files = new Map()
					this.chuchaiApplyForm = {
						startDate: '',
						endDate: '',
						chufa: '',
						destination: '',
						jiaotong: "铁路交通",
						reason: '',
						attaches: [],
						bao: []
					}

					this.currentIndex = 1

					this.getNewestRecord()
				} catch (err) {
					uni.showToast({title: err.message || 'error'})
				}
			},
			async revertApply(idx) {
				try {
					await websock.revertChuchaiApply({id: this.applyRecord[idx].id})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({title: err.message || 'error'})
				}
			},
			seeDetail(idx) {
				uni.navigateTo({url: `/pages/task/chuchaiApplyDetail?id=${this.applyRecord[idx].id}`})
			}
		}
	}
</script>

<style>
@import '../common/common.css';
</style>
